package Simpleblog::Controller::Blog;

use strict;
use warnings;
use base 'Catalyst::Controller';

=head1 NAME

Simpleblog::Controller::Blog - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 auto

must login before enter here.

=cut

sub auto : Private{
    my ($self, $c) = @_;
    unless ($c->user_exists) {
        $c->res->redirect("/logon/login");
        return;
    }


}

=head2 delete

delete one blog

=cut

sub delete : Local{
    my ($self, $c, $id) = @_;
    return unless ($id>0);
    $c->stash->{id} = $id;
    $c->stash->{template} = 'blog/confirm_delete.tt2';
    
}

sub do_delete : Local{
    my ($self, $c, $id) = @_;
    my $blog = $c->model("Simpleblog::Articles")
        ->single({id=>$id, user_id => $c->user->obj->id});
    
    if ($blog) {
        $blog->delete;
    }
    $c->res->redirect($c->uri_for('/self'));
}

=head2 create_or_edit

create blog or edit a blog

=cut

sub create_or_edit : LocalRegex('^(create|edit)$') {
    my ($self, $c, $id) = @_;

    $id ||= 0;
    return if $id <0;
    
    # if id is >0, then it need edit
    if ($id) {
        my $blog = $c->model("Simpleblog::Articles")
            ->find({id=>$id,user_id=>$c->user->obj->id});
        $c->stash($blog->get_columns);
    }


    # Create the widget and set the action for the form
    my $w = $self->make_blog_widget($c);


    # Write form to stash variable for use in template
    $c->stash->{widget_result} = $w->result;

    # Set the template
    $c->stash->{template} = 'blog/blog_form.tt2';

}


=head2 blog_create_update_do

Build an HTML::Widget form for blog creation and updates

=cut

sub blog_create_update_do : Local {
    my ($self, $c) = @_;



    # Create the widget
    my $w = $self->make_blog_widget($c);


    # Validate the form parameters
    my $result = $w->process($c->req);

    # Retrieve the data from the form
    my $subject   = $result->params->{subject};
    my $body  = $result->params->{body};
    my $id = $result->params->{id};


    # Write form (including validation error messages) to
    # stash variable for use in template
    $c->stash->{widget_result} = $result;

    # Were their validation errors?
    if ($result->has_errors) {
        # Warn the user at the top of the form that there were errors.
        # Note that there will also be per-field feedback on
        # validation errors because of '$w->process($c->req)' above.
        $c->stash->{error_msg} = 'Validation errors!';

        # Set the template
        $c->stash->{template} = 'blog/blog_form.tt2';
        return;

    } 
    
    # Everything validated OK, so do the create or update
    # Call create() or update. Pass the table
    # columns/field values we want to set as hash values
    my $blog_record = {
        user_id => $c->user->obj->id,
        subject => $subject,
        body    => $body,
    };

    if ($id) {
        $c->model('Simpleblog::Articles')->find({id => $id,user_id => $c->user->obj->id})
            ->update($blog_record);
        $c->res->body('blog updated');

    }
    else {
        $c->model('Simpleblog::Articles')->create($blog_record);
        $c->res->body('blog created');
    }
    return;

}


=head2 make_blog_widget

Build an HTML::Widget form for blog creation and updates

=cut

sub make_blog_widget {
    my ($self, $c) = @_;

    # Create an HTML::Widget to build the form
    my $w = $c->widget('blog_form')->method('post');
    $w->action($c->uri_for('blog_create_update_do'));

    # Create the form feilds
    my $subject = $w->element('Textfield', 'subject'  );
    $subject->label('Subject')->size(50);
    $subject->value($c->stash->{subject});

    my $body = $w->element('Textarea', 'body'  );
    $body->label('Body');
    $body->value($c->stash->{body});
    
    $w->element('Submit',    'submit' )->value('submit');
    $w->element('Hidden','id')->value($c->stash->{id});

    $w->constraint(All     => qw/subject/)
        ->message('Required. ');

    $w->constraint(Length  => qw/subject/)->min(2)->max(255)
        ->message('Must be between 4 and 255 characters. ');

    $w->filter( TrimEdges  => "subject" );
    $w->filter( TrimEdges  => "body"    );

    # Return the widget
    return $w;
}

=head2 display

display blog

=cut

sub display : Local {
    my ($self, $c, $username) = @_;
    # can check $username here

    my $user = $c->model("Simpleblog::Users")->find({name => $username});
    $self->do_display($c, $user);
}

=head2 do_display

display blog

=cut


sub do_display : Private {
    my ($self, $c, $user) = @_;

    # get all blogs;
    my @blogs = $c->model("Simpleblog::Articles")->search(
        {user_id => $user->id},
        {order_by => "created_at desc"});
    # show latest blog first;
    $c->stash->{user} = $user;
    $c->stash->{blogs} = \@blogs;
    $c->stash->{template} = "blog/display.tt2";
    

}

=head1 AUTHOR

chylli,,,

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
